﻿//------------------------------------------------------------------------------
// Written for CP2011 Project @ JCU, 2011
// By Drewan O'Brien
// 
// Executes a login request by first checking if supplied username exists followed
// by checking if the password is correct.  If both of these conditions are true
// the client is notified that the login request was succesful.
//------------------------------------------------------------------------------

using System;
using System.Linq;

using System.Collections.Generic;
using BluSteamServer.Model.DataAccessLayer;

namespace BluSteamServer.Model.TransactionImplementation
{
    public class LoginTransaction : Transaction
    {
        #region Fields

        private readonly string _username;
        private readonly string _password;
        private bool _validated;

        #endregion

        #region Properties

        public bool Validated
        {
            get { return _validated; }
        }

        #endregion

        #region Constructors

        public LoginTransaction(string username, string password)
        {
            _username = username;
            _password = password;
        }

        #endregion

        #region Methods

        public void Validate()
        {
            // search for user requesting to login
            Dictionary<string, object> user = 
                new DataAccessObject().GetRecordByAttribute("Users", "username", _username);

            // username incorrect or user not yet registered
            if (user.Count == 0)
            {
                ConnectionManager.Instance.RemoveConnection(_username);
                string message = string.Format("$CP2011~{0}~RESPONSE~INCORRECT_USERNAME", _username);
                Network.Send(_username, message);
                return;
            }

            // user password is incorrect
            if (user["password"] as string != _password) 
            {
                ConnectionManager.Instance.RemoveConnection(_username);
                string message = string.Format("$CP2011~{0}~RESPONSE~INCORRECT_PASSWORD", _username);
                Network.Send(_username, message);
                return;
            }

            _validated = true;
        }

        public void Execute()
        {
            if (_validated)
            {
                // notify client that login was successful
                string message = string.Format("$CP2011~{0}~RESPONSE~LOGIN_SUCCESS", _username);
                Network.Send(_username, message);
            }
        }

        #endregion
    }
}
